import Vue from 'vue'
import Vuex from 'vuex'
import {
	getStore,
	setStore,
	clearStore
} from '@/utils/store'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		token: getStore({
			name: 'token'
		}) || '', //token
		userInfo: getStore({
			name: 'userInfo'
		}) || '',
		skip: getStore({
			name: 'skip'
		}) || '',
		trainData: getStore({
			name: 'trainData'
		}) || [],
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token;
			setStore({
				name: 'token',
				content: state.token
			})
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo;
			setStore({
				name: 'userInfo',
				content: state.userInfo
			})
		},
		SET_SKIP: (state, skip) => {
			state.skip = skip;
			setStore({
				name: 'skip',
				content: state.skip
			})
		},
		SET_TRAINDATA: (state, payload) => {
			var tData = state.trainData.find(p => p.pid === payload.pid)
			if(tData != undefined){
				if(payload.actionIndex != undefined){
					tData.actionIndex = payload.actionIndex
				}
				if(payload.actionId != undefined){
					tData.actionId = payload.actionId
				}
				if(payload.actionCount != undefined){
					tData.actionCount = payload.actionCount
				}
				if(payload.trainRecordId != undefined){
					tData.trainRecordId = payload.trainRecordId
				}
				if(payload.sensorMaxAngles != undefined){
					tData.sensorMaxAngles = payload.sensorMaxAngles
				}
			} else {
				tData = JSON.parse(JSON.stringify(payload))
				state.trainData.push(tData)
			}
			setStore({
				name: 'trainData',
				content: state.trainData
			})
			console.log(state.trainData.length)
		},
		RM_TRAINDATA_BYPID: (state, pid) => {
			var tIndex = state.trainData.findIndex(p => p.pid === pid)
			if(tIndex != -1){
				state.trainData.splice(tIndex, 1)
			}
			setStore({
				name: 'trainData',
				content: state.trainData
			})
			console.log(state.trainData.length)
		},
		Logout: (state) => {
			state.token = state.userInfo = '';
			clearStore();
		},
	},
	actions: {
	},
	getters: {
		token: state => state.token,
		userInfo: state => state.userInfo,
		skip: state => state.skip,
		getTrainDataByPid: (state) => (pid) =>{
			return state.trainData.find(p => p.pid === pid)
		},
		getTrainData: state => state.trainData
	},
	modules: {}
})
